#include <iostream>
#include <string>
#include <cstring>
#include <sstream>

//c
#include <arpa/inet.h>

/*
    字节序: https://www.yanbinghu.com/2018/10/02/25450.html
    关于计算机使用小端序 (低位在前), 而网络序为大端序 (高位在前)
*/
std::string GetBytesOrder(char* head, size_t size) {
    std::string result;
    for (size_t i = 0; i < size; i++, head++) {
        std::stringstream ss;
        uint8_t a = static_cast<uint8_t>(*head);

        char hexcode[3] = { 0 };
        sprintf(hexcode, "%x", a);
        if (std::strlen(hexcode) == 1) {
            hexcode[1] = hexcode[0];
            hexcode[0] = '0';
        }
        ss << hexcode;

        result += ss.str();
    }

    return result;
}


int main() {
    int a = 0x12345678;
    //小端序(主机)
    std::cout << "host long ByteOrder: " << GetBytesOrder((char*)&a, 4) << std::endl;

    //大端序(网络)
    a = htonl(a);
    std::cout << "htonl(host to net long) ByteOrder: " << GetBytesOrder((char*)&a, 4) << std::endl;

    //小端序(主机)
    a = ntohl(a);
    std::cout << "ntohl(net to host long) ByteOrder: " << GetBytesOrder((char*)&a, 4) << std::endl;

    //ip to addr
    in_addr addr;
    char ip[16] = "192.168.0.1";
    inet_pton(AF_INET, ip, &addr);
    std::cout << "addr is: " << std::hex << addr.s_addr << std::dec << std::endl;
    std::cout << "addr ByteOrder(big-endian): " << GetBytesOrder((char*)(&addr.s_addr), 4) << std::endl;

    //addr to ip
    addr.s_addr = 0x0100a8c0;
    inet_ntop(AF_INET, &addr, ip, sizeof(ip));
    std::cout << "ip is: " << ip << std::endl;

    return 0;
}